import { copyText, useThrottle, downText, getTime } from "../utilities";
import { settings } from "../settings";
import { notes, length, reset, exportNotes } from "./notes";
import { useState, useEffect, useRef, useCallback } from "preact/hooks";
import { toast } from "../signals";
import {
  Copy,
  Trash2,
  Eraser,
  Plus,
  ChevronLeft,
  ChevronRight,
  Calendar,
  Clock,
  Mail,
  Hash,
  Send,
  AtSign,
} from "lucide-preact";

const NoteButton = ({ onClick, children }) => (
  <button
    type="button"
    class="btn btn-warning in-[.dark]:btn-secondary *:size-4"
    onClick={onClick}
  >
    {children}
  </button>
);

const Note = () => {
  const [pageCount, setPageCount] = useState(1);
  const [showSms, setShowSms] = useState(false);
  const [showEmail, setShowEmail] = useState(false);
  const [content, setContent] = useThrottle(notes.value[0]);
  const [phoneNumber, setPhoneNumber] = useThrottle("");
  const [email, setEmail] = useThrottle("");
  const textRef = useRef(null);
  const countRef = useRef(pageCount);

  const updateContent = useCallback((text) => {
    const original = [...notes.value];
    original[countRef.current - 1] = text;
    notes.value = original;
  }, []);

  const updateInput = useCallback(() => {
    if (textRef.current) {
      textRef.current.value = notes.value[countRef.current - 1];
    }
  }, [textRef]);

  useEffect(() => {
    updateContent(content);
  }, [content, updateContent]);

  useEffect(() => {
    countRef.current = pageCount;
    updateInput();
  }, [pageCount, updateInput]);

  useEffect(() => {
    if (reset.value) {
      setPageCount(1);
      updateInput();
    }
  }, [reset.value, updateInput]);

  return (
    <div class={`card w-69 in-[.light]:bg-yellow-100`}>
      <div class="card-body">
        <div class="card-actions *:btn-sm *:btn-ghost *:btn-square place-items-center justify-between">
          <NoteButton
            onClick={() => {
              const original = [...notes.value];
              original.splice(pageCount, 0, "");
              notes.value = original;
              setPageCount(pageCount + 1);
            }}
          >
            <Plus />
          </NoteButton>
          <NoteButton
            onClick={() => {
              setPageCount(pageCount === 1 ? length.value : pageCount - 1);
            }}
          >
            <ChevronLeft />
          </NoteButton>
          <button
            type="button"
            onClick={() => {
              downText(exportNotes(), "便签.txt");
            }}
            class="appearance-none text-sm/8 select-none"
          >
            {pageCount} / {length}
          </button>
          <NoteButton
            onClick={() => {
              setPageCount(pageCount === length.value ? 1 : pageCount + 1);
            }}
          >
            <ChevronRight />
          </NoteButton>
          <NoteButton
            onClick={() => {
              if (length.value === 1) {
                if (textRef.current) {
                  textRef.current.value = "";
                  setContent("");
                }
              } else {
                const original = [...notes.value];
                original.splice(pageCount - 1, 1);
                notes.value = original;
                setPageCount(pageCount === 1 ? length.value : pageCount - 1);
              }
            }}
          >
            <Trash2 />
          </NoteButton>
        </div>
        <textarea
          class="textarea textarea-warning in-[.dark]:textarea-secondary textarea-ghost"
          placeholder="写点什么呢..."
          rows={settings.value.widget.noteRows}
          ref={textRef}
          onInput={(event) => {
            setContent(event.target.value);
          }}
        />
        <div class="card-actions *:btn-sm *:btn-ghost *:btn-square place-items-center justify-between gap-1">
          <NoteButton
            onClick={() => {
              if (textRef.current) {
                copyText(textRef.current.value);
              }
            }}
          >
            <Copy />
          </NoteButton>
          <NoteButton
            onClick={() => {
              if (textRef.current) {
                const timeDate = getTime();
                const newContent = `${content}${timeDate[0]}-${timeDate[1]}-${timeDate[2]} 星期${timeDate[10]}`;
                textRef.current.value = newContent;
                setContent(newContent);
              }
            }}
          >
            <Calendar />
          </NoteButton>
          <NoteButton
            onClick={() => {
              if (textRef.current) {
                const timeDate = getTime();
                const newContent = `${content}${timeDate[3]}:${timeDate[4]}:${timeDate[5]}`;
                textRef.current.value = newContent;
                setContent(newContent);
              }
            }}
          >
            <Clock />
          </NoteButton>
          <NoteButton
            onClick={() => {
              setShowEmail(false);
              setEmail("");
              setShowSms(!showSms);
            }}
          >
            <Mail />
          </NoteButton>
          <NoteButton
            onClick={() => {
              setShowSms(false);
              setPhoneNumber("");
              setShowEmail(!showEmail);
            }}
          >
            <AtSign />
          </NoteButton>
          <NoteButton
            onClick={() => {
              if (textRef.current) {
                textRef.current.value = "";
                setContent("");
              }
            }}
          >
            <Eraser />
          </NoteButton>
        </div>
        {showSms ? (
          <div class="join w-full place-items-center">
            <label class="input input-xs input-ghost input-warning in-[.dark]:input-secondary join-item">
              <Hash class="size-4" />
              <input
                type="tel"
                placeholder="110"
                onInput={(event) => {
                  setPhoneNumber(event.target.value);
                }}
              />
            </label>
            <button
              class="btn btn-warning btn-ghost btn-sm btn-square in-[.dark]:btn-secondary join-item"
              onClick={() => {
                if (phoneNumber === "" || content === "") {
                  toast("请输入内容和发送号码");
                  return;
                }
                location.assign(
                  `sms:${encodeURIComponent(phoneNumber)}?body=${encodeURIComponent(content)}`,
                );
              }}
            >
              <Send class="size-4" />
            </button>
          </div>
        ) : (
          void 0
        )}
        {showEmail ? (
          <div class="join w-full place-items-center">
            <label class="input input-xs input-ghost input-warning in-[.dark]:input-secondary join-item">
              <AtSign class="size-4" />
              <input
                type="email"
                placeholder="hello@example.com"
                onInput={(event) => {
                  setEmail(event.target.value);
                }}
              />
            </label>
            <button
              class="btn btn-warning btn-ghost btn-sm btn-square in-[.dark]:btn-secondary join-item"
              onClick={() => {
                const lines = content.split("\n");
                if (email === "" || lines.length < 2) {
                  toast(
                    "请输入正确的内容和邮箱地址，内容至少两行，第一行作为主题",
                  );
                  return;
                }
                location.assign(
                  `mailto:${encodeURIComponent(email)}?subject=${encodeURIComponent(lines[0])}&body=${encodeURIComponent(lines.slice(1).join("\n"))}`,
                );
              }}
            >
              <Send class="size-4" />
            </button>
          </div>
        ) : (
          void 0
        )}
      </div>
    </div>
  );
};

export default Note;
